﻿#region

using System;

#endregion

namespace TSharp.Core.Message.MessageImpl
{
    /// <summary>
    ///     情景实现类
    ///     <para>by tangjingbo at 2009/12/14 21:37</para>
    /// </summary>
    internal class SituationImpl : ISituation
    {
        #region ISituation 成员

        private readonly WeakReference senderObj = new WeakReference(null);

        public SituationImpl()
        {
        }

        public SituationImpl(object senderObj)
        {
            this.senderObj.Target = senderObj;
        }

        public IMessageResult<TMessage> Broadcast<TMessage>(TMessage message)
        {
            var tran = new TransmitterImpl<TMessage>(senderObj, message);
            return HandleMassage(tran);
        }

        public IMessageResult<TMessage> Broadcast<TMessage>(TMessage message, int maxDistance)
        {
            var tran = new TransmitterImpl<TMessage>(senderObj, message);
            tran.MaxDistance = maxDistance;
            return HandleMassage(tran);
        }

        private IMessageResult<TMessage> HandleMassage<TMessage>(TransmitterImpl<TMessage> tran)
        {
            return MessageListenerManage.HandleMassage(tran);
        }

        #endregion

        #region 消息监听注册

        public IRegisterHandle<TMessage> Register<TMessage>(IHandle<TMessage> listener,
                                                            int order)
        {
            return MessageListenerManage.Register(listener, order);
        }

        public IRegisterHandle[] Register(IHandle listener)
        {
            return MessageListenerManage.Register(listener);
        }

        public IRegisterHandle<TMessage> Register<TMessage>(IHandle<TMessage> listener)
        {
            return Register(listener, int.MaxValue);
        }


        public void UnRegister(IHandle listener)
        {
            MessageListenerManage.UnRegister(listener);
        }

        public IRegisterHandle<TMessage> RegMessageListener<TMessage>(IHandle<TMessage> listener,
                                                                      bool autoUnReg)
        {
            return Register(listener, int.MaxValue);
        }

        #endregion
    }
}